package com.chl.picture;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.io.File;
import java.io.IOException;

import org.bytedeco.javacpp.Loader;
import org.bytedeco.opencv.opencv_java;
import org.opencv.core.*;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.photo.Photo;

/**
 * 精准获取图片上的文字，进行清晰化处理
 * 
 * @author 006006
 *
 */
public class OcrPicText {

	static {
		
//		Loader.load(opencv_java.class);
//		System.loadLibrary("jniopenblas");
		// Load the OpenCV native library
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	}

	public static void main(String[] args) {
		// Path to the input image
		String imagePath = "D:\\openCV\\img\\pic_2.jpg";

		// Read the image file
		Mat src = Imgcodecs.imread(imagePath);

		if (src.empty()) {
			System.out.println("Could not open or find the image!");
			return;
		}

//		// Enhance the image clarity using unsharp masking
//		Mat blurred = new Mat();
//		Imgproc.GaussianBlur(src, blurred, new Size(0, 0), 3);
//		Mat sharpened = new Mat();
//		Core.addWeighted(src, 1.5, blurred, -0.5, 0, sharpened);

		
		
		// 步骤2：图像预处理
        Mat gray = new Mat();
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);

        // 直方图均衡化（增强对比度）
        Mat equalized = new Mat();
        Imgproc.equalizeHist(gray, equalized);

        // 去噪（非局部均值滤波）
        Mat denoised = new Mat();
        Photo.fastNlMeansDenoising(equalized, denoised);

        // 锐化处理
        Mat kernel = new Mat(3, 3, CvType.CV_32F);
        kernel.put(0, 0, new float[]{
                0, -1, 0,
                -1, 5, -1,
                0, -1, 0
        });
        Mat sharpened = new Mat();
        Imgproc.filter2D(denoised, sharpened, -1, kernel);

//        // 步骤3：可选 - 图像超分（使用 OpenCV DNN 模块加载 SR 模型）
//        // 注意：需要 SR 模型文件（如 EDSR_x2.pb）
//        Mat upscaled = sharpened.clone();
//        try {
//            DnnSuperResImpl sr = DnnSuperResImpl.create();
//            sr.readModel("models/EDSR_x2.pb");
//            sr.setModel("edsr", 2);
//            sr.upsample(sharpened, upscaled);
//        } catch (Exception e) {
//            System.out.println("超分模型加载失败，跳过超分步骤。");
//        }
		// Save the enhanced image
		Imgcodecs.imwrite("enhanced_image.jpg", sharpened);
		

		// Perform OCR on the enhanced image
		ITesseract instance = new Tesseract();

		// Save the enhanced image to a temporary file
		File tempFile = null;
		try {
			tempFile = File.createTempFile("enhanced_image", ".jpg");
			Imgcodecs.imwrite(tempFile.getAbsolutePath(), sharpened);
			// Set the data path where tessdata is located
			instance.setDatapath("D:\\openCV\\tessdata\\");
			// Specify the language
			instance.setLanguage("chi_sim");

			// Do OCR on the image
			String result = instance.doOCR(tempFile);
			System.out.println("识别结果：---\n\r"+result);
		} catch (TesseractException e) {
			System.err.println(e.getMessage());
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}
}
